let registeredOrder = require("../model/registeredOrder");
let {
  Router
} = require("express");
let router = new Router();
router.use(require("../middleware/auth.js"));

/* 
状态：1==》待支付
2==>待取号
3==》已取号
4==》已取消
5==》已退号
*/

// 添加挂号订单
// /api/registeredOrder
router.post("/", async (req, res) => {
  // 获取参数
  const user = req.userInfo._id;
  let {
    patientID,
    department,
    state,
    doctor,
    date,
    number,
    price,
    time,
    hospitalname,
    position
  } = req.body;
  // 判断参数是否为空
  if (
    patientID == "" ||
    department == "" ||
    state == "" ||
    doctor == "" ||
    date == "" ||
    number == "" ||
    price == "" ||
    time == '' ||
    hospitalname == '' ||
    position == ''
  ) {
    res.status(400).json({
      msg: "缺少参数",
    });
    return;
  }
  let data = await registeredOrder.create({
    patientID,
    department,
    state,
    doctor,
    date,
    number,
    price,
    time,
    hospitalname,
    position
  });
  res.status(200).json({
    msg: "添加成功",
    data
  });
});

// 查询就诊人全部订单
router.get("/patient_id", async (req, res) => {
  const {
    patientID
  } = req.query;
  // console.log("----id----", patientID);
  const datas = await registeredOrder
    .find({
      patientID
    })
    .populate(["patientID"]);
  res.status(200).json({
    msg: "查询成功",
    datas,
  });
});

// 删除订单
router.delete("/", async (req, res) => {
  const {
    _id
  } = req.query;
  const datas = await registeredOrder.findOneAndDelete({
    _id
  });
  res.status(200).json({
    msg: "删除成功",
    datas,
  });
});

// 修改订单状态
router.patch("/", async (req, res) => {
  const {
    _id,
    state
  } = req.body;
  await registeredOrder.findOneAndUpdate({
    _id
  }, {
    state
  });
  res.status(200).json({
    msg: "修改成功"
  });
});

//根据——id查询数据
router.get("/getinfo", async (req, res) => {
  const {
    _id,
  } = req.query;
  console.log(_id);
  let data = await registeredOrder.findOne({
    _id
  }).populate(["patientID"]);

  res.status(200).json({
    msg: "查询成功",
    data
  });
});
module.exports = router;